// src/views/tongji/componentLoader.js
import LoadingComponent from "./LoadingComponent.vue";
import ErrorComponent from "./ErrorComponent.vue";

class ComponentLoader {
  constructor() {
    this.componentCache = new Map();
    this.preloadedComponents = this.preloadAllComponents();
  }

  // 预加载所有组件
  preloadAllComponents() {
    const components = {};

    try {
      // 使用 require.context 批量导入组件
      const requireComponent = require.context(
        '/', // 组件目录的相对路径
        false,           // 是否查询子目录
        /\.vue$/         // 匹配文件的正则表达式
      );

      requireComponent.keys().forEach(fileName => {
        // 获取组件名称
        const componentName = fileName
          .replace(/^\.\//, '')     // 移除开头的 "./"
          .replace(/\.\w+$/, '');   // 移除文件扩展名

        // 导入组件
        components[componentName] = requireComponent(fileName).default;
      });
    } catch (error) {
      console.error('预加载组件失败:', error);
    }

    return components;
  }

  // 获取组件
  getComponent(name) {
    if (this.componentCache.has(name)) {
      return this.componentCache.get(name);
    }

    // 创建异步组件
    const asyncComponent = () => {
      // 如果已经预加载过，直接返回
      if (this.preloadedComponents[name]) {
        return Promise.resolve(this.preloadedComponents[name]);
      }

      // 否则动态导入
      return import(`./${name}.vue`);
    };

    // 根据组件名称决定是否需要延迟
    let component;
    let loadingTime = name.substr(4) * 100 + 500
    component = () => ({
      component: new Promise((resolve) => {
        setTimeout(() => {
          asyncComponent().then(resolve);
        }, loadingTime);
      }),
      loading: LoadingComponent,
      error: ErrorComponent,
      delay: 200,
      timeout: 3000
    });

    this.componentCache.set(name, component);
    return component;
  }

  // 批量获取组件
  getComponents(componentList) {
    const components = {};
    componentList.forEach(name => {
      components[name] = this.getComponent(name);
    });
    return components;
  }
}

export default new ComponentLoader();
